package telex;
/*
 * Query.java
 *
 * Copyright (c) 2007-2008 Colin Bayer, Douglas Downey, Oren Etzioni,
 *   University of Washington Computer Science and Engineering
 * 
 * See the file "COPYING" in the root directory of this distribution for
 * full licensing information.
 */

import java.util.*;

public class Query implements Comparable<Query> {
	public Query(String[] aWords) {
		mWords = new QueryString(aWords);
		mResult = -1;
		mUserFeatures = new HashMap<String, String>();
		mUserDataString = null;
	}
	
	public Query(String[] aWords, long aResult, String aUserData) {
		mWords = new QueryString(aWords);
		mResult = aResult;
		mUserFeatures = null;
		mUserDataString = aUserData;
	}
	
	public int compareTo(Query aOther) {
		if (aOther == null) throw new NullPointerException();
		return mWords.compareTo(aOther.mWords);
	}
	public boolean equals(Query aOther) {
		if (aOther == null) return false;
		return compareTo(aOther) == 0;
	}
	
	public int hashCode() {
		return mWords.hashCode();
	}

	public boolean isFinished() { return (mResult >= 0); }

	public void setUserFeature(String aName, String aVal) {
		if (aName == null) return;
		if (mUserFeatures == null && !parseUserDataString(mUserDataString)) return;
		
		mUserFeatures.put(aName, aVal);
	}
	
	public QueryString getQueryString() { return mWords; }
	public int getArity() { return mWords.length(); }
	
	public long getResult() { return mResult; }
	public String getUserFeature(String aName) {
		if (mUserFeatures == null && !parseUserDataString(mUserDataString)) return null;
		
		return mUserFeatures.get(aName); 
	} 
	
	public String getUserDataString() {
		if (mUserFeatures == null) return mUserDataString;
		
		String rv = new String();
		
		for (Map.Entry<String, String> e : mUserFeatures.entrySet()) {
			rv += e.getKey() + ":" + e.getValue() + ";";
		}
		
		return rv;
	}
	private boolean parseUserDataString(String aUDString) {
		mUserFeatures = new HashMap<String, String>();
		
		for (String s : aUDString.split(";")) {
			String[] parts = s.split(":");
			
			if (parts.length < 2) continue;
			mUserFeatures.put(parts[0], parts[1]);
		}
		
		return true;
	}
	
	public String toString() {
		return "(" + mWords.getFlattened(", ") + "): count " + mResult + "; user data \"" + getUserDataString() + "\"";
	}
	
	/*public void setBundle(QueryBundle aBundle) 
		{ mBundle = aBundle; }*/

	public void finish(long aResult) {
		mResult = aResult;
		//if (mBundle != null) mBundle.queryDone(this);
	}

	private QueryString mWords;
	//private QueryBundle mBundle;
	private long mResult;
	
	private HashMap<String, String> mUserFeatures;
	private String mUserDataString;
}
